package xyz.sunne.service;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.sunne.entity.SysRole;
import xyz.sunne.exception.RequestException;
import xyz.sunne.mapper.SysRoleMapper;

import java.util.Date;

/**
 * @author Sunne
 * @version 1.0
 * @date 2021/9/24 0024
 */
@Service
public class SysRoleService extends BaseService<SysRoleMapper,SysRole>{
    //添加角色
    @Transactional
    public void add(SysRole sysRole){
        SysRole role = this.getByKey(SysRole::getName, sysRole.getName());
        if(role!=null) throw RequestException.fail("同名角色已经存在");
        role = new SysRole();
        BeanUtils.copyProperties(sysRole,role,"id","created","permission");
        role.setCreated(new Date());
        role.setPermission(JSON.toJSONString(sysRole.getPers()));
        if(!this.save(role)){
            throw RequestException.fail("角色添加失败");
        }
    }


    @Transactional
    public void update(SysRole sysRole,String id){
        SysRole role = this.getById(id);
        if(role==null) throw RequestException.fail("更新角色不存在");
        SysRole findRole = this.getByKey(SysRole::getName, sysRole.getName());
        if(findRole!=null && !findRole.getId().equals(id)) throw RequestException.fail("同名角色已经存在");
        role.setName(sysRole.getName());
        role.setPermission(JSON.toJSONString(sysRole.getPers()));
        if(!this.updateById(role)){
            throw RequestException.fail("角色更新失败");
        }
    }

}
